﻿using UnityEngine.UI;
using UnityEngine;
using System;

namespace QFramework
{
    public interface ITransitionSystem : ISystem
    {
        void Fade(FadeState state, float step = 0);
        void Fade(float stepIn = 0, float stepOut = 0, Action callback = null);
    }
    public class TransitionSystem : AbstractSystem, ITransitionSystem
    {
        private FadeNum mFade = new FadeNum();
        private Image mFadeImg;
        private float mFadeStep;
        private Color mAlpha;

        void ITransitionSystem.Fade(FadeState state, float step)
        {
            mFadeStep = step;
            mFade.SetState(state, () => PublicMono.Instance.OnUpdate -= Update);
            PublicMono.Instance.OnUpdate += Update;
        }
        void ITransitionSystem.Fade(float stepIn, float stepOut, Action callback)
        {
            mFadeStep = stepIn;
            mFade.SetState(FadeState.FadeIn, () =>
            {
                callback?.Invoke();
                mFadeStep = stepOut;
                mFade.SetState(FadeState.FadeOut, () => PublicMono.Instance.OnUpdate -= Update);
            });
            PublicMono.Instance.OnUpdate += Update;
        }
        private void Update()
        {
            if (mFadeImg == null) InitFadeImg();
            var step = mFadeStep;
            if (mFadeStep == 0) step = Time.deltaTime;
            mAlpha.a = mFade.Update(step);
            mFadeImg.color = mAlpha;
        }
        protected override void OnInit() { }

        private void InitFadeImg()
        {
            var o = new GameObject("FadeImg");
            var canvas = GameObject.Find("Canvas");
            if (canvas == null) throw new Exception("无法找到场景中的Canvas 请先创建画布");

            o.transform.SetParent(canvas.transform);
            mFadeImg = o.AddComponent<Image>();
            mFadeImg.color = mAlpha = Color.black;
            mFadeImg.rectTransform.anchoredPosition = Vector2.zero;
            mFadeImg.rectTransform.sizeDelta = canvas.GetComponent<CanvasScaler>().referenceResolution;
            mFadeImg.raycastTarget = false;
        }
    }
}